#include "drv_beep.h"

#define BEEP_ON  1
#define BEEP_OFF 0

//disp驱动部分命令（与背光相关，内核目录：/include/video/sunxi_display2.h)
#define	DISP_LCD_SET_BRIGHTNESS     0x102
#define DISP_LCD_GET_BRIGHTNESS     0x103
#define	DISP_LCD_BACKLIGHT_ENABLE   0x104
#define	DISP_LCD_BACKLIGHT_DISABLE  0x105

static uint8_t beep_status = BEEP_OFF;
uint16_t beep_timer = 0;

void fun_set_light_level(float level)
{
    int fd;
    unsigned long args[3] = {0};
    /*打开disp设备文件*/
    fd = open("/dev/disp", O_RDWR, 0);
    if(fd < 0) {
        printf("open /dev/disp failed.\n");
        return;
    }

    int brightness = level * 255;

    if(brightness < 0 || brightness > 255) {
        brightness = 125;
    }

    /*参数数组填参*/
    args[0] = 0;
    args[1] = brightness; // 背光值(本人配置里最高为255)
    args[2] = 0;          // 暂时用不到的参数
    ioctl(fd, DISP_LCD_SET_BRIGHTNESS, args);
    close(fd);
    return;
}

void fun_set_beep_level(int level)
{
    char cmd_buff[100] = {0};

    if(level){
        system("echo 170000 > /sys/class/pwm/pwmchip0/pwm4/duty_cycle");
        // sprintf(cmd_buff, "echo %d > /sys/class/pwm/pwmchip0/pwm4/duty_cycle", g_UserSet.BeepEn * 1700);
        system(cmd_buff);
    }else{
        system("echo 0 > /sys/class/pwm/pwmchip0/pwm4/duty_cycle");
    }
}

void fun_BeepN(int ms)
{
    g_UserSet.blk_time_count = g_UserSet.blk_time * 60;
    if(!g_UserSet.BeepEn){
        fun_set_beep_level(BEEP_OFF);
        return;
    }
    beep_timer = ms;
    fun_set_beep_level(BEEP_ON);
    beep_status = BEEP_ON;
}

void fun_BeepN2(int ms)
{
    g_UserSet.blk_time_count = g_UserSet.blk_time * 60;
    if(!g_UserSet.BeepEn){
        fun_set_beep_level(BEEP_OFF);
        return;
    }
    beep_timer = ms;
    fun_set_beep_level(BEEP_ON);
    beep_status = BEEP_ON;
}

void *thread_timer(void *argc)
{
    while (1)
    {
        sleep_ms(10);
        if(beep_timer){
            beep_timer--;
            if(beep_timer == 0){
                fun_set_beep_level(BEEP_OFF);
                beep_status = BEEP_OFF;
            }
        }
    }
}

void beep_start(void)
{
    int res = 0;
    pthread_t tid_timer;

    system("echo 4 > /sys/class/pwm/pwmchip0/export");
    system("echo 340000 > /sys/class/pwm/pwmchip0/pwm4/period");
    // system("echo 170000 > /sys/class/pwm/pwmchip0/pwm4/duty_cycle");
    system("echo 1 > /sys/class/pwm/pwmchip0/pwm4/enable");
    // system("echo normal > /sys/class/pwm/pwmchip0/pwm4/polarity");

    res = pthread_create(&tid_timer , NULL , thread_timer , NULL);
    if(res){
        perror("thread_timer creat error!\r\n");
    }
}